package cz.tsystems.data;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;

import com.fasterxml.jackson.databind.JsonNode;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteDBProvider extends SQLiteOpenHelper   {
	private Context theContext;
	static private String DB_NAME = "mchi.db";
	private SQLiteDatabase mchiDataBase;

    public SQLiteDBProvider(Context context) {
        super(context, DB_NAME, null, 1);
        this.theContext = context;
    }
    
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
	}    
    
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{
 
    	boolean dbExist = checkDataBase();
 
    	if(dbExist){
    		//do nothing - database already exist
    	}else{
 
    		//By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
    		SQLiteDatabase db = this.getReadableDatabase();
        	
        	if (db.isOpen()){
        		db.close();
        	} 
        	try {
 
    			copyDataBase();
 
    		} catch (IOException e) {
 
        		throw new Error("Error copying database");
 
        	}
    	}
 
    } 
    
    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
 
    	SQLiteDatabase checkDB = null;
 
    	try{
    		String myPath = this.theContext.getDatabasePath(DB_NAME).getAbsolutePath();
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 
    	}catch(SQLiteException e){
 
    		//database does't exist yet.
 
    	}
 
    	if(checkDB != null){
 
    		checkDB.close();
 
    	}
 
    	return checkDB != null ? true : false;
    }
    
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{
 
    	//Open your local db as the input stream
    	
    	InputStream myInput = theContext.getAssets().open("databases/mchiBase.db");
 
    	// Path to the just created empty db
    	String outFileName = this.theContext.getDatabasePath(DB_NAME).getAbsolutePath();
 
    	//Open the empty db as the output stream
    	OutputStream myOutput = new FileOutputStream(outFileName);
 
    	//transfer bytes from the inputfile to the outputfile
    	byte[] buffer = new byte[1024];
    	int length;
    	while ((length = myInput.read(buffer))>0){
    		myOutput.write(buffer, 0, length);
    	}
 
    	//Close the streams
    	myOutput.flush();
    	myOutput.close();
    	myInput.close();
 
    }
 
    public void openDataBase() throws SQLException{
 
    	//Open the database
        String myPath = this.theContext.getDatabasePath(DB_NAME).getAbsolutePath();
    	mchiDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READWRITE);
 
    }
    
    public Cursor executeQuery(String query)
    {
    	return this.executeQuery(query, new String [] {});
    }
    
    public Cursor executeQuery(String query, String[] podmin)
    {
    	if(!query.contains("_id"))
    		query = query.replaceAll("^SELECT", "SELECT _ROWID_ AS _id, ");
    	
    	Cursor cur= mchiDataBase.rawQuery(query, podmin);
    	if(cur.getCount() > 0)
    		cur.moveToFirst();
    	return cur;    	    	
    }
    
    public String getDBStrutVersion()
    {
    	Cursor cur = this.executeQuery("SELECT DB_STRUCTURE_VERSION FROM SYS_CONFIG");
    	if(cur.getCount() == 0)
    		return "NO_RECORD";
    	return cur.getString(1);
    }
    
    public String getDBVersion()
    {
    	Cursor cur = this.executeQuery("SELECT DB_VERSION FROM SYS_CONFIG");
    	if(cur.getCount() == 0)
    		return "NO_RECORD";
   		return cur.getString(1);
    }    
    
    
    public void insertTableData(String tableName, Iterator<JsonNode> dataArray)
    {
    	boolean loadFieldNames = false;
    	String fields = " ( '", values = " ";
		while (dataArray.hasNext()) {
			JsonNode object = dataArray.next();
			String valuesPrefix = " UNION SELECT ";
			
			if(!loadFieldNames)
			{
				valuesPrefix = " SELECT ";
				loadFieldNames = true;
				Iterator<String> fieldNames = object.fieldNames();
				while(fieldNames.hasNext())
					fields += fieldNames.next() + "', '";
				int pos = fields.lastIndexOf(", ");
				fields = fields.replaceAll(", '$", " )");
				Log.d("fields", fields);
			}
			
			values += valuesPrefix + getNodValues(object) + " ";
		}
		
		values = values.replaceAll(", $", " ");
		if(loadFieldNames && mchiDataBase.isOpen())
		{
//			mchiDataBase.execSQL("DROP TABLE IF EXISTS " + tableName);DELETE FROM
			mchiDataBase.execSQL("DELETE FROM " + tableName);
			mchiDataBase.execSQL("INSERT INTO '"+tableName+"' "+fields+" "+values);
		}
		
		
    }
    
    
    private String getNodValues(JsonNode object)
    {
    	String values = " ";
    	Iterator<JsonNode> ite = object.elements();
    	
    	while(ite.hasNext())
    	{
    		JsonNode jn = ite.next();
    		
    		if(jn.isNull())
    			values += "NULL, ";
    		else if(jn.isInt())
    			values += jn.intValue() + ", ";
    		else if(jn.isDouble())
    			values += jn.doubleValue() + ", ";
    		else if(jn.isTextual())
    			values += "'"+jn.textValue() + "', ";
    		else if(jn.isBoolean())
    			values += (jn.booleanValue())?"1, ":"0, ";
    	}
    	
    	return values.replaceAll(", $", " ");
    }

}


